package com.example.service;

import com.example.entity.College;
import com.example.exception.CustomException;
import com.example.mapper.CollegeMapper;
import com.example.mapper.MajorMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CollegeService {
    @Resource
    private CollegeMapper collegeMapper;
    @Resource
    private MajorMapper majorMapper;

    public List<College> selectAll(College college) {
        return collegeMapper.selectAll(college);
    }

    public PageInfo<College> selectPage(College college, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<College> list = collegeMapper.selectAll(college);
        return PageInfo.of(list);
    }

    public void add(College college) {
        if (collegeMapper.countByCollegeName(college.getCollegeName()) > 0){
            throw new CustomException("400","学院已存在");
        }
        collegeMapper.insert(college);
    }

    public void update(College college) {
        College existingCollege = collegeMapper.selectById(college.getCollegeId());
        //  如果名称没有改变，直接通过
        if (existingCollege.getCollegeName().equals(college.getCollegeName())) {
            return;
        }
        if (collegeMapper.countByCollegeName(college.getCollegeName()) > 0){
            throw new CustomException("400","学院已存在");
        }
        collegeMapper.update(college);
    }

    public void delete(Integer collegeId) {
        if (majorMapper.countByCollegeId(collegeId) > 0){
            throw new CustomException("400","存在关联专业");
        }
        collegeMapper.delete(collegeId);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer collegeId : ids) {
            if (majorMapper.countByCollegeId(collegeId) > 0) {
                throw new CustomException("400", "选中学院中存在关联专业");
            }
        }
        for (Integer collegeId : ids) {
            collegeMapper.delete(collegeId);
        }
    }
}
